import { StyleSheet, Text, View, ScrollView, Pressable, TouchableOpacity, ImageBackground } from 'react-native';
import React, { useRef, useCallback, useState, useMemo } from 'react';
import LinearGradient from 'react-native-linear-gradient';
import FastImage from '@d11/react-native-fast-image';
import { SwiperFlatList } from 'react-native-swiper-flatlist';
import { useTranslation } from 'react-i18next';
import { useNavigation, useFocusEffect } from '@react-navigation/native';
import { useCameraPermission } from 'react-native-vision-camera';
import { FocusAwareStatusBar, Dropdown, BlinkingCircle } from '~/components';
import { useAddMessage, useBlockBackHandler, useBindDeviceList, useDeviceType } from '~/common';
import { observer, userStore, appStore, webSocketStore } from '~/store';
import { px2dp, scale, statusBarHeight, isIos, width, onePx } from '~/utils/px2dp';
import { getAge } from '~/utils/formatDate';
import { getDoctorListApi, getUserCourseByTitle, getDeviceBindBodyList, getUserUseTitleIdApi } from '~/api/acupoints';
import { unReadCtAllApi } from '~/api/message';
import AddDoctorModal from './components/AddDoctorModal';

export default observer(() => {
    useBindDeviceList();
    useDeviceType();
    useBlockBackHandler();
    const { t } = useTranslation();
    const { hasPermission, requestPermission } = useCameraPermission();
    const options = [
        { val: 1, label: t('Acupoints.title') },
        { val: 2, label: t('Acupoints.t75') },
    ];
    const navigation = useNavigation<any>();
    const [titleId, setTitleId] = useState(21); // 大包ID，暂时以21为主
    const handleSelect = (selected: { val: number; label: string }) => {
        if (selected.val == 2) {
            userStore.selectRole('Main');
            navigation.navigate('Main');
        }
    };
    const [listData, setListData] = useState([
        {
            id: 1,
            name: t('AddDeviceScreen.t15'),
            user_id: '',
            device_id: '',
            body_index: 1,
            armarium_device_chang: '',
            course_id: '',
            device_image: 'https://bjy-crmeb.oss-cn-shenzhen.aliyuncs.com/attach/2024/06/ab18d20240619155430143.png',
        },
        {
            id: 2,
            name: t('AddDeviceScreen.t16'),
            user_id: '',
            device_id: '',
            body_index: 2,
            armarium_device_chang: '',
            course_id: '',
            device_image: 'https://bjy-crmeb.oss-cn-shenzhen.aliyuncs.com/attach/2024/06/ab18d20240619155430143.png',
        },
        {
            id: 3,
            name: t('AddDeviceScreen.t17'),
            user_id: '',
            device_id: '',
            body_index: 3,
            armarium_device_chang: '',
            course_id: '',
            device_image: 'https://bjy-crmeb.oss-cn-shenzhen.aliyuncs.com/attach/2024/06/ab18d20240619155430143.png',
        },
        {
            id: 4,
            name: t('AddDeviceScreen.t18'),
            user_id: '',
            device_id: '',
            body_index: 4,
            armarium_device_chang: '',
            course_id: '',
            device_image: 'https://bjy-crmeb.oss-cn-shenzhen.aliyuncs.com/attach/2024/06/ab18d20240619155430143.png',
        },
        {
            id: 5,
            name: t('AddDeviceScreen.t19'),
            user_id: '',
            device_id: '',
            body_index: 5,
            armarium_device_chang: '',
            course_id: '',
            device_image: 'https://bjy-crmeb.oss-cn-shenzhen.aliyuncs.com/attach/2024/06/ab18d20240619155430143.png',
        },
    ]);
    const timesArray = [
        { end_time: '01:00', start_time: '23:00', title: t('Acupoints.t29'), content: t('Acupoints.t30') },
        { end_time: '03:00', start_time: '01:00', title: t('Acupoints.t31'), content: t('Acupoints.t32') },
        { end_time: '05:00', start_time: '03:00', title: t('Acupoints.t33'), content: t('Acupoints.t34') },
        { end_time: '07:00', start_time: '05:00', title: t('Acupoints.t35'), content: t('Acupoints.t36') },
        { end_time: '09:00', start_time: '07:00', title: t('Acupoints.t37'), content: t('Acupoints.t38') },
        { end_time: '11:00', start_time: '09:00', title: t('Acupoints.t39'), content: t('Acupoints.t40') },
        { end_time: '13:00', start_time: '11:00', title: t('Acupoints.t41'), content: t('Acupoints.t42') },
        { end_time: '15:00', start_time: '13:00', title: t('Acupoints.t43'), content: t('Acupoints.t44') },
        { end_time: '17:00', start_time: '15:00', title: t('Acupoints.t45'), content: t('Acupoints.t46') },
        { end_time: '19:00', start_time: '17:00', title: t('Acupoints.t47'), content: t('Acupoints.t48') },
        { end_time: '21:00', start_time: '19:00', title: t('Acupoints.t49'), content: t('Acupoints.t50') },
        { end_time: '23:00', start_time: '21:00', title: t('Acupoints.t51'), content: t('Acupoints.t52') },
    ];
    // 获取用户大包id
    const getTitleId = async () => {
        const result = await getUserUseTitleIdApi();
        setTitleId(result.returnData); // 拿到大包id
        await getBindDeviceXueWei(result.returnData);
    };
    // 获取绑定穴位的列表
    const getBindDeviceXueWei = async (id) => {
        try {
            const res = await getDeviceBindBodyList({ title_id: id });
            if (res.status !== 1) {
                return;
            }
            if (res.list.length == 0) {
                Toast.show({ content: t('Acupoints.t27'), layout: 'top' });
            } else {
                listData.forEach((itemB) => {
                    const matchedItem = res.list.find((itemA) => itemA.body_index === String(itemB.body_index)); // 注意 body_index 转换成字符串
                    if (matchedItem) {
                        itemB.id = matchedItem.id;
                        itemB.device_id = matchedItem.device_id;
                        itemB.user_id = matchedItem.user_id;
                        itemB.armarium_device_chang = matchedItem.armarium_device_chang;
                        itemB.course_id = matchedItem.course_id;
                        // itemB.name = matchedItem.course_name || itemB.name;
                    }
                });
                const isDeviceSnEmpty = res.list.some((item: any) => {
                    return !item.armarium_device_chang;
                });
                if (!isDeviceSnEmpty) {
                    getMyCourse({ device_sn: res.list[0].armarium_device_chang, title_id: id });
                }
                setListData(listData);
            }
        } catch (error) {}
    };

    // 判断是否有疗程
    const [baseCourseInfo, setBaseCourseInfo] = useState({
        name: '',
        use_day: 0,
        total_day: 0,
        base_course_img: '',
    }); // 获取大包信息
    const isCourse = useMemo(() => {
        const num = baseCourseInfo?.total_day - baseCourseInfo?.use_day;
        return num > 0;
    }, [baseCourseInfo?.total_day, baseCourseInfo?.use_day]);

    const [parameterList, setParameterList] = useState([]);
    const mergeByStartTime = (data) => {
        const mergedMap = new Map();
        data.forEach((item) => {
            const { start_time } = item;
            if (!mergedMap.has(start_time)) {
                mergedMap.set(start_time, { ...item });
            } else {
                const existingItem = mergedMap.get(start_time);
                let index = 2;
                while (existingItem[`acupoint${index}`]) {
                    index++;
                }
                Object.keys(item).forEach((key) => {
                    if (key !== 'start_time') {
                        existingItem[`${key}${index}`] = item[key];
                    }
                });
            }
        });

        return Array.from(mergedMap.values());
    };
    // 获取我的疗程
    const { addMessage, loading, error } = useAddMessage();
    const addmessages = async () => {
        try {
            const response = await addMessage({
                type: 3,
                title: t('Acupoints.t61'),
                content: t('Acupoints.t60'),
            });
        } catch (error) {}
    };
    const getMyCourse = (params) => {
        getUserCourseByTitle(params).then((res) => {
            if (res.status !== 1) {
                Toast.show({ content: res.msg });
            } else {
                const courseInfo = res.base_course[0];
                if (courseInfo.total_day - courseInfo.use_day <= 7) {
                    // Notice.show(t('Acupoints.t60'));
                    addmessages();
                }
                setBaseCourseInfo(courseInfo);
                const groupedList: any = mergeByStartTime(res.parameter_list);
                setParameterList(groupedList);
                checkStatus(listData, res.parameter_list);
            }
        });
    };

    // 查看疗程详情
    const goCourseDetailes = () => {
        navigation.navigate('CourseDetailes', { base_course_img: baseCourseInfo?.base_course_img });
    };
    // 添加医生
    const modalRef: any = useRef();
    const addDoctor = () => {
        if (userStore.userDeviceYY01Data.length == 0) {
            Toast.show({ content: t('Acupoints.t57') });
            return;
        }
        if (doctorData.length > 0) {
            navigation.navigate('DoctorDetailes', { userInfo: selectDoctor });
        } else {
            modalRef.current.openModal();
        }
    };
    const addDoctorCallback = () => {
        getDoctorList();
    };
    // 获取医生列表
    const [doctorData, setDoctorData] = useState([]); // 医生列表
    const [selectDoctor, setSelectDoctor] = useState({
        armarium_science_user_birthday: '',
        wx_head_portrait: '',
        armarium_science_user_name: '',
        armarium_science_user_mobile: '',
    });
    // 选择医生信息
    const getDoctorList = () => {
        getDoctorListApi().then((res) => {
            setDoctorData(res.data);
            if (res.data.length > 0) {
                setSelectDoctor(res.data[0]);
            }
        });
    };

    // 添加设备
    const addDevice = () => {
        navigation.navigate('AddDeviceScreen', { titleId });
    };

    // 添加子设备
    const addSubDevice = (row) => {
        navigation.navigate('AddDeviceScreen', { device_sn: row.device_sn, titleId });
    };

    // 返回对应时间
    const getTitleAndContentByTime = (time) => {
        return (
            timesArray.find((item) => {
                const start = item.start_time;
                const end = item.end_time;
                if (start < end) {
                    return time >= start && time < end;
                } else {
                    return time >= start || time < end;
                }
            }) || {}
        );
    };
    // 查看设备详情
    const goDeviceDetailes = (row) => {
        if (!row.armarium_device_chang) {
            navigation.navigate('AddDeviceScreen', {
                titleId,
                device_sn: userStore.userDeviceYY01Data.length > 0 ? userStore.userDeviceYY01Data[0].device_sn : '',
            });
            return;
        }
        navigation.navigate('AcupoinDeviceDetailes', {
            title_id: titleId,
            device_sn: row.armarium_device_chang,
            course_id: row.course_id,
            yyDevicesn: userStore.userDeviceYY01Data[0]?.device_sn || '',
        });
    };

    // 获取当前时间检测状态
    function checkStatus(array1, parameter_list) {
        function updateStatus() {
            const currentTime = new Date();
            const currentTotalSeconds =
                currentTime.getHours() * 3600 + currentTime.getMinutes() * 60 + currentTime.getSeconds();
            const updatedArray = array1.map((item) => {
                const matchingParams = parameter_list.filter((param) => param.course_id === item.course_id);
                let status = 0;
                let remainingTime = 0;
                let startTime = '';
                let endTime = '';
                let foundMatch = false;
                let closestTimeDiff = Infinity;
                let closestStartTime = '';
                let closestEndTime = '';
                for (const param of matchingParams) {
                    const startTimeParts = param.start_time.split(':').map(Number);
                    const endTimeParts = param.end_time.split(':').map(Number);
                    const startTotalSeconds = startTimeParts[0] * 3600 + startTimeParts[1] * 60;
                    const endTotalSeconds = endTimeParts[0] * 3600 + endTimeParts[1] * 60;
                    if (
                        (startTotalSeconds <= currentTotalSeconds && currentTotalSeconds <= endTotalSeconds) ||
                        (endTotalSeconds < startTotalSeconds &&
                            (currentTotalSeconds >= startTotalSeconds || currentTotalSeconds <= endTotalSeconds))
                    ) {
                        status = 1;
                        remainingTime =
                            endTotalSeconds >= currentTotalSeconds
                                ? endTotalSeconds - currentTotalSeconds
                                : 24 * 3600 - currentTotalSeconds + endTotalSeconds;
                        startTime = param.start_time;
                        endTime = param.end_time;
                        foundMatch = true;
                        break;
                    }
                    let timeDiff;
                    if (currentTotalSeconds < startTotalSeconds) {
                        timeDiff = startTotalSeconds - currentTotalSeconds;
                    } else {
                        timeDiff = 24 * 3600 - currentTotalSeconds + startTotalSeconds;
                    }
                    if (timeDiff < closestTimeDiff) {
                        closestTimeDiff = timeDiff;
                        closestStartTime = param.start_time;
                        closestEndTime = param.end_time;
                    }
                }

                if (!foundMatch && closestTimeDiff !== Infinity) {
                    startTime = closestStartTime;
                    endTime = closestEndTime;
                }
                if (!foundMatch && startTime === '') {
                }

                return { ...item, status, remainingTime, startTime, endTime };
            });
            setListData(updatedArray);
        }

        updateStatus();
        setInterval(updateStatus, 1000);
    }
    // 查看五穴同频数据
    const isDeviceSnEmpty = useMemo(
        () =>
            listData.some((item: any) => {
                return !item.armarium_device_chang;
            }),
        [listData],
    );
    const goDeviceWebView = () => {
        if (isDeviceSnEmpty) return Toast.show({ content: t('Acupoints.t58'), layout: 'top' });
        const newArray = listData.map((item, index) => {
            return { course_id: item.course_id, device_id: item.device_id };
        });
        navigation.navigate('DeviceDateView', {
            category: 'acupoint',
            acupointParams: JSON.stringify(newArray),
        });
    };
    // 获取消息
    const [messageTotal, setMessageTotal] = useState(0);
    const getMessageList = () => {
        unReadCtAllApi({ type: '3,4,5' }).then((res) => {
            if (res.data > 0) {
                setMessageTotal(res.data.length);
                // Notice.show(`${res.data.length}${t('Acupoints.t59')}`, 'success');
            }
        });
    };
    useFocusEffect(
        useCallback(() => {
            getTitleId();
            getDoctorList();
            getMessageList();
        }, []),
    );
    return (
        <View style={styles.container}>
            <FocusAwareStatusBar translucent={true} barStyle={'light-content'} />
            <LinearGradient
                style={styles.linearGradient}
                colors={['#0B0322', '#110828']}
                start={{ x: 0, y: 0 }}
                end={{ x: 0, y: 1 }}>
                <View style={[styles.header, styles.row, styles.between]}>
                    <Dropdown
                        options={options}
                        textStyle={styles.optionsStyle}
                        onSelect={handleSelect}
                        iconColor="#fff"
                    />

                    <View style={[styles.row, styles.between]}>
                        <TouchableOpacity
                            style={styles.header_icons}
                            onPress={() => navigation.navigate('MessageScreen')}>
                            <FastImage
                                style={styles.icons}
                                source={{
                                    uri: 'https://bjy-crmeb.oss-cn-shenzhen.aliyuncs.com/attach/2025/02/4d047202502221113404583.png',
                                    priority: FastImage.priority.high,
                                }}
                                resizeMode={FastImage.resizeMode.contain}
                            />
                            {messageTotal > 0 && (
                                <View style={styles.bige}>
                                    <Text style={styles.bigeText}>{messageTotal >= 99 ? '...' : messageTotal}</Text>
                                </View>
                            )}
                        </TouchableOpacity>
                        <TouchableOpacity style={styles.header_icons} onPress={goDeviceWebView}>
                            <FastImage
                                style={styles.icons}
                                source={{
                                    uri: 'https://bjy-crmeb.oss-cn-shenzhen.aliyuncs.com/attach/2025/02/403e8202502221113417248.png',
                                    priority: FastImage.priority.high,
                                }}
                                resizeMode={FastImage.resizeMode.contain}
                            />
                        </TouchableOpacity>
                    </View>
                </View>
                <ScrollView showsVerticalScrollIndicator={false} contentContainerStyle={styles.contentContainerStyle}>
                    <View style={styles.content}>
                        <ImageBackground
                            resizeMode="contain"
                            source={{
                                uri: 'https://bjy-crmeb.oss-cn-shenzhen.aliyuncs.com/attach/2025/02/2e61b202502221017257186.png',
                            }}
                            style={styles.bg}>
                            <View style={styles.listBoxContent}>
                                {listData.map((item: any, index) => {
                                    const isSecondRow = index >= 1;
                                    const isSecondRow1 = index >= 1 && index < 3;
                                    const isSecondRow2 = index >= 3 && index <= 4;
                                    return (
                                        <TouchableOpacity
                                            onPress={() => goDeviceDetailes(item)}
                                            key={item.id}
                                            style={!isSecondRow && { width: width - px2dp(48) }}>
                                            <ImageBackground
                                                resizeMode="contain"
                                                style={[
                                                    styles.listBox,
                                                    isSecondRow1 && { marginTop: px2dp(80) },
                                                    isSecondRow2 && { marginTop: px2dp(240) },
                                                    isSecondRow && { width: (width - px2dp(280)) / 2 },
                                                ]}
                                                source={{
                                                    uri: 'https://bjy-crmeb.oss-cn-shenzhen.aliyuncs.com/attach/2025/02/6dcf3202502221133346148.png',
                                                }}>
                                                {isCourse && item.armarium_device_chang ? (
                                                    <View>
                                                        <Text style={styles.t1}>
                                                            {item.status > 0 ? t('Acupoints.t1') : t('Acupoints.t53')}
                                                        </Text>
                                                        {item.status == 0 && (
                                                            <Text style={styles.courseName}>
                                                                {item.startTime}~{item.endTime}
                                                            </Text>
                                                        )}
                                                        <Text style={styles.courseName}>{item.name}</Text>
                                                        {item.remainingTime > 0 && (
                                                            <Text style={styles.t2}>
                                                                {t('Acupoints.t2')}：
                                                                {Math.floor(item?.remainingTime / 60)}
                                                                {t('Acupoints.t3')}
                                                            </Text>
                                                        )}
                                                    </View>
                                                ) : (
                                                    <View>
                                                        <Text style={styles.t1}>{t('Acupoints.t55')}</Text>
                                                        <Text style={styles.courseName}>{item.name}</Text>
                                                    </View>
                                                )}
                                            </ImageBackground>
                                        </TouchableOpacity>
                                    );
                                })}
                            </View>
                            <View style={styles.circle1}>
                                <BlinkingCircle />
                            </View>
                            <View style={styles.circle2}>
                                <BlinkingCircle />
                            </View>
                            <View style={styles.circle3}>
                                <BlinkingCircle />
                            </View>
                            <View style={styles.circle4}>
                                <BlinkingCircle />
                            </View>
                            <View style={styles.circle5}>
                                <BlinkingCircle />
                            </View>
                        </ImageBackground>

                        <View style={[styles.row, styles.alCenter, styles.between, { marginTop: px2dp(64) }]}>
                            {/* 医生信息 */}
                            <Pressable style={styles.card} onPress={addDoctor}>
                                <View style={[styles.row, styles.alCenter]}>
                                    <Text style={styles.card_name}>{t('Acupoints.t4')}</Text>
                                    <View
                                        style={[
                                            styles.active_border,
                                            doctorData?.length == 0 && { backgroundColor: '#e8e8e8' },
                                        ]}>
                                        <Text
                                            style={[
                                                styles.active_border_text,
                                                doctorData?.length == 0 && { color: '#a4a4a4' },
                                            ]}>
                                            {doctorData?.length == 0 ? t('Acupoints.t6') : t('Acupoints.t5')}
                                        </Text>
                                    </View>
                                </View>
                                {doctorData?.length > 0 ? (
                                    <View style={[styles.userTop, styles.row, styles.alCenter]}>
                                        <FastImage
                                            style={styles.avatar}
                                            source={{
                                                uri:
                                                    selectDoctor?.wx_head_portrait ||
                                                    'https://bjy.oss-cn-shenzhen.aliyuncs.com/pic/20230413/3041681348866.png',
                                                priority: FastImage.priority.high,
                                            }}
                                            resizeMode={FastImage.resizeMode.contain}
                                        />
                                        <View style={{ marginLeft: px2dp(12) }}>
                                            <View style={[styles.row, styles.alCenter]}>
                                                <Text
                                                    style={[styles.card_title, { width: px2dp(120) }]}
                                                    numberOfLines={1}>
                                                    {selectDoctor?.armarium_science_user_name}
                                                </Text>
                                                <View style={[styles.row, styles.alCenter, { marginLeft: px2dp(12) }]}>
                                                    <FastImage
                                                        style={styles.birthdayIcons}
                                                        source={{
                                                            uri: 'https://bjy-crmeb.oss-cn-shenzhen.aliyuncs.com/attach/2025/02/cfd3d202502221525008152.png',
                                                            priority: FastImage.priority.high,
                                                        }}
                                                        resizeMode={FastImage.resizeMode.contain}
                                                    />
                                                    <Text>{getAge(selectDoctor?.armarium_science_user_birthday)}</Text>
                                                </View>
                                            </View>
                                            <View style={[styles.row, styles.alCenter, { marginTop: px2dp(12) }]}>
                                                <FastImage
                                                    style={styles.birthdayIcons}
                                                    source={{
                                                        uri: 'https://bjy-crmeb.oss-cn-shenzhen.aliyuncs.com/attach/2023/11/4e62d202311061625351306.png',
                                                        priority: FastImage.priority.high,
                                                    }}
                                                    resizeMode={FastImage.resizeMode.contain}
                                                />
                                                <Text>{selectDoctor.armarium_science_user_mobile}</Text>
                                            </View>
                                        </View>
                                    </View>
                                ) : (
                                    <View style={[styles.row, styles.alCenter, { height: px2dp(106) }]}>
                                        <Text style={styles.empity}>{t('Acupoints.t24')}</Text>
                                    </View>
                                )}
                            </Pressable>

                            {/* yy01信息 */}
                            <View style={[styles.card]}>
                                {userStore.userDeviceYY01Data.length > 0 ? (
                                    <SwiperFlatList
                                        style={styles.swiper}
                                        autoplay={false}
                                        showPagination={false}
                                        paginationActiveColor="#1DCE87"
                                        paginationStyleItem={{ width: px2dp(10), height: px2dp(10) }}
                                        paginationStyle={{ height: px2dp(4) }}
                                        data={userStore.userDeviceYY01Data || []}
                                        renderItem={({ item }) => {
                                            return (
                                                <Pressable style={styles.swiperItem} onPress={() => addSubDevice(item)}>
                                                    <View style={[styles.row, styles.alCenter]}>
                                                        <Text style={styles.card_name}>
                                                            {appStore.app.language == 'zh'
                                                                ? item.num + t('Acupoints.t63')
                                                                : t('Acupoints.t63') + item.num}
                                                        </Text>
                                                        {/* <View
                                                            style={[
                                                                styles.active_border,
                                                                // device_online == 0 && { backgroundColor: '#e8e8e8' },
                                                            ]}>
                                                            <Text
                                                                style={[
                                                                    styles.active_border_text,
                                                                    // device_online == 0 && { color: '#a4a4a4' }, // 离线 "t10": "离线"
                                                                ]}>
                                                                {t('Acupoints.t9')}
                                                            </Text>
                                                        </View> */}
                                                    </View>
                                                    <View style={[styles.userTop, styles.row, styles.alCenter]}>
                                                        <FastImage
                                                            style={styles.avatar}
                                                            source={{
                                                                uri: 'https://bjy-crmeb.oss-cn-shenzhen.aliyuncs.com/attach/2025/02/db52f202502221533365635.png',
                                                                priority: FastImage.priority.high,
                                                            }}
                                                            resizeMode={FastImage.resizeMode.contain}
                                                        />
                                                        <View style={{ marginLeft: px2dp(12) }}>
                                                            <Text style={styles.device_sn} numberOfLines={1}>
                                                                {item.device_sn}
                                                            </Text>
                                                            <View
                                                                style={[
                                                                    styles.row,
                                                                    styles.alCenter,
                                                                    { marginTop: px2dp(4) },
                                                                ]}>
                                                                <Text style={styles.replace}>{t('Acupoints.t11')}</Text>
                                                            </View>
                                                        </View>
                                                    </View>
                                                </Pressable>
                                            );
                                        }}
                                    />
                                ) : (
                                    <TouchableOpacity
                                        style={styles.swiperItem}
                                        onPress={() => {
                                            if (hasPermission) {
                                                navigation.navigate('ScanBleDevice');
                                            } else {
                                                requestPermission();
                                            }
                                        }}>
                                        <View style={[styles.row, styles.alCenter]}>
                                            <Text style={styles.card_name}>{t('Acupoints.t8')}</Text>
                                            <View style={[styles.active_border, { backgroundColor: '#e8e8e8' }]}>
                                                <Text
                                                    style={[
                                                        styles.active_border_text,
                                                        { color: '#a4a4a4' }, // 离线 "t10": "离线"
                                                    ]}>
                                                    {t('Acupoints.t22')}
                                                </Text>
                                            </View>
                                        </View>
                                        <View style={[styles.userTop, styles.row, styles.alCenter]}>
                                            <FastImage
                                                style={styles.avatar}
                                                source={{
                                                    uri: 'https://bjy-crmeb.oss-cn-shenzhen.aliyuncs.com/attach/2025/02/db52f202502221533365635.png',
                                                    priority: FastImage.priority.high,
                                                }}
                                                resizeMode={FastImage.resizeMode.contain}
                                            />
                                            <View style={{ marginLeft: px2dp(12) }}>
                                                <View style={[styles.row, styles.alCenter, { marginTop: px2dp(4) }]}>
                                                    <Text style={styles.replace}>{t('Acupoints.t23')}</Text>
                                                </View>
                                            </View>
                                        </View>
                                    </TouchableOpacity>
                                )}
                            </View>
                        </View>
                        {/* 疗程信息 */}
                        <View style={[styles.card, { width: '100%', marginTop: px2dp(12), padding: px2dp(-24) }]}>
                            {/* {isCourse && (
                                <Pressable
                                    style={styles.switchCourse}
                                    onPress={() => handleAddDevice(userStore.userDeviceYY01Data[0].device_sn)}>
                                    <Text style={styles.switchText}>{t('Acupoints.t12')}</Text>
                                </Pressable>
                            )} */}
                            <View style={styles.cardContent}>
                                {isCourse ? (
                                    <View>
                                        <View style={[styles.row, styles.alCenter]}>
                                            <Text style={styles.card_title} numberOfLines={1}>
                                                {baseCourseInfo?.name}
                                            </Text>
                                            <View style={[styles.active_border]}>
                                                <Text style={[styles.active_border_text]}>{t('Acupoints.t13')}</Text>
                                            </View>
                                        </View>
                                        <Text style={styles.days}>
                                            {t('Acupoints.t14')}
                                            {baseCourseInfo?.total_day - baseCourseInfo?.use_day}
                                            {t('Acupoints.t15')}
                                        </Text>
                                    </View>
                                ) : (
                                    <View>
                                        <Text style={styles.card_title}>{t('Acupoints.t28')}</Text>
                                        <Text style={styles.days}>
                                            {t('Acupoints.t14')}0{t('Acupoints.t15')}
                                        </Text>
                                    </View>
                                )}

                                <View style={styles.line}></View>
                                {isCourse ? (
                                    <View style={[styles.row, styles.alCenter, styles.bottom]}>
                                        <TouchableOpacity onPress={goCourseDetailes}>
                                            <Text style={styles.bottom_text}>{t('Acupoints.t16')}</Text>
                                        </TouchableOpacity>
                                        <TouchableOpacity onPress={() => navigation.navigate('BuyMall')}>
                                            <Text style={[styles.bottom_text, { color: '#FF6430' }]}>
                                                {t('Acupoints.t17')}
                                            </Text>
                                        </TouchableOpacity>
                                    </View>
                                ) : (
                                    <TouchableOpacity onPress={addDevice}>
                                        <Text style={styles.activeCourse}>{t('Acupoints.t56')}</Text>
                                    </TouchableOpacity>
                                )}
                            </View>
                        </View>
                        {/* 疗程详情 */}
                        {isCourse && (
                            <View style={[styles.courseDetailes, styles.row, styles.alCenter, styles.between]}>
                                {parameterList.map((item: any, index) => {
                                    const result: any = getTitleAndContentByTime(item.start_time);
                                    return (
                                        <LinearGradient
                                            key={item?.id}
                                            style={styles.courseCard}
                                            colors={['#FFFFFF', '#E9FAF3']}
                                            start={{ x: 0, y: 0 }}
                                            end={{ x: 0, y: 1 }}>
                                            <View
                                                style={[
                                                    styles.row,
                                                    styles.alCenter,
                                                    styles.between,
                                                    { marginBottom: px2dp(24) },
                                                ]}>
                                                <Text style={styles.time}>{item?.start_time}</Text>
                                                <Text style={styles.byTimeText}>{result?.content}</Text>
                                            </View>

                                            <View style={[styles.row, styles.alCenter, styles.between]}>
                                                <Text style={styles.t3}>
                                                    {t('Acupoints.t20')}:{item?.course_name}
                                                </Text>
                                                <View style={[styles.active_border]}>
                                                    <Text style={[styles.active_border_text]}>
                                                        {item?.start_duration}
                                                        {t('Acupoints.t3')}
                                                    </Text>
                                                </View>
                                            </View>
                                            {item?.course_name2 && (
                                                <View
                                                    style={[
                                                        styles.row,
                                                        styles.alCenter,
                                                        styles.between,
                                                        { marginTop: px2dp(12) },
                                                    ]}>
                                                    <Text style={styles.t3}>
                                                        {t('Acupoints.t21')}:{item?.course_name2}
                                                    </Text>
                                                    <View
                                                        style={[
                                                            styles.active_border,
                                                            { backgroundColor: 'rgba(255, 100, 48, 0.12)' },
                                                        ]}>
                                                        <Text style={[styles.active_border_text, { color: '#FF6430' }]}>
                                                            {item?.start_duration2 + t('Acupoints.t3')}
                                                        </Text>
                                                    </View>
                                                </View>
                                            )}

                                            <View style={styles.line}></View>
                                            <Text style={styles.tips}>{item.desc}</Text>
                                        </LinearGradient>
                                    );
                                })}
                            </View>
                        )}
                    </View>
                </ScrollView>
            </LinearGradient>
            {/* 添加医生 */}
            <AddDoctorModal ref={modalRef} actionCallback={addDoctorCallback} />
        </View>
    );
});

const SWIPERWIDTH = (width - px2dp(64)) / 2 - px2dp(48);
const styles = StyleSheet.create({
    row: {
        flexDirection: 'row',
    },
    alCenter: {
        alignItems: 'center',
    },
    between: {
        justifyContent: 'space-between',
    },
    container: {
        flex: 1,
    },
    contentContainerStyle: {
        flexGrow: 1,
        marginTop: '18%',
        marginHorizontal: px2dp(24),
        paddingBottom: '60%',
    },
    linearGradient: {
        flex: 1,
        paddingTop: isIos() ? statusBarHeight + px2dp(40) : statusBarHeight,
    },
    header: {
        position: 'absolute',
        top: isIos() ? '8%' : '6%',
        zIndex: 1,
        marginHorizontal: px2dp(24),
        width: width - px2dp(48),
    },
    optionsStyle: {
        color: '#fff',
        fontSize: scale(32),
        fontWeight: 'bold',
        textAlign: 'left',
    },
    header_icons: {
        marginLeft: px2dp(24),
        position: 'relative',
    },
    bige: {
        position: 'absolute',
        left: 16,
        top: -6,
        backgroundColor: 'red',
        justifyContent: 'center',
        alignItems: 'center',
        width: px2dp(38),
        height: px2dp(34),
        borderRadius: px2dp(30),
    },
    bigeText: {
        color: '#fff',
        fontSize: scale(22),
    },
    icons: {
        width: px2dp(50),
        height: px2dp(50),
    },
    content: {
        flex: 1,
    },
    bgContainer: {
        position: 'relative',
    },
    bg: {
        resizeMode: 'cover',
        width: width - px2dp(48), // 宽度占满屏幕
        height: width * (19 / 14),
        position: 'relative',
    },
    listBoxContent: {
        flexGrow: 1,
        justifyContent: 'space-between',
        flexWrap: 'wrap',
        flexDirection: 'row',
        height: width * (19 / 16),
    },
    listBox: {
        padding: px2dp(12),
        height: (width * (19 / 16)) / 4,
        width: (width - 140) / 2,
        alignItems: 'center',
        justifyContent: 'center',
    },
    t1: {
        color: '#66EFFE',
        fontSize: scale(24),
    },
    courseName: {
        color: '#66EFFE',
        fontSize: scale(26),
        fontWeight: 'bold',
        marginTop: px2dp(12),
        lineHeight: px2dp(32),
    },
    t2: {
        fontSize: scale(26),
        color: '#FFFFFF',
        marginTop: px2dp(12),
    },
    circle1: {
        position: 'absolute',
        top: '22%',
        left: '46%',
    },
    circle2: {
        position: 'absolute',
        top: '50%',
        left: '24%',
    },
    circle3: {
        position: 'absolute',
        top: '50%',
        right: '24%',
    },
    circle4: {
        position: 'absolute',
        bottom: px2dp(24),
        left: '34%',
    },
    circle5: {
        position: 'absolute',
        bottom: px2dp(24),
        right: '34%',
    },
    card: {
        backgroundColor: '#fff',
        padding: px2dp(24),
        borderRadius: px2dp(24),
        width: (width - px2dp(64)) / 2,
    },
    swiper: {
        flex: 1,
        width: SWIPERWIDTH,
    },
    swiperItem: {
        width: SWIPERWIDTH,
    },
    card_title: {
        color: '#1A1A1A',
        fontSize: scale(28),
        fontWeight: 'bold',
        width: '80%',
    },

    card_name: {
        color: '#1A1A1A',
        fontSize: scale(24),
        fontWeight: 'bold',
    },
    device_sn: {
        width: '90%',
        color: '#1A1A1A',
        fontSize: scale(24),
    },
    active_border: {
        backgroundColor: 'rgba(29, 206, 135, 0.12)',
        borderRadius: px2dp(12),
        marginLeft: px2dp(12),
        paddingHorizontal: px2dp(12),
        paddingVertical: px2dp(8),
    },
    active_border_text: {
        color: '#1DCE87',
        fontSize: scale(24),
    },
    userTop: {
        marginTop: px2dp(24),
    },
    avatar: {
        width: px2dp(80),
        height: px2dp(80),
    },
    birthdayIcons: {
        width: px2dp(30),
        height: px2dp(30),
        marginRight: px2dp(8),
    },
    replace: {
        color: '#FF6430',
    },
    switchCourse: {
        backgroundColor: '#1877FF',
        width: px2dp(180),
        paddingVertical: px2dp(8),
        alignSelf: 'flex-end',
        borderBottomLeftRadius: px2dp(40),
        borderTopRightRadius: px2dp(24),
    },
    switchText: {
        textAlign: 'center',
        color: '#fff',
        fontSize: scale(28),
    },
    cardContent: {
        margin: px2dp(24),
    },
    days: {
        fontSize: scale(24),
        color: '#666666',
        marginVertical: px2dp(12),
    },
    line: {
        borderBottomWidth: onePx,
        borderColor: '#eee',
        marginVertical: px2dp(24),
    },
    bottom: {
        justifyContent: 'space-around',
    },
    bottom_text: {
        color: '#626262',
        fontSize: scale(30),
        fontWeight: 'bold',
    },
    courseDetailes: {
        flexWrap: 'wrap',
        marginTop: px2dp(12),
    },
    courseCard: {
        width: (width - px2dp(56)) / 2,
        backgroundColor: '#fff',
        padding: px2dp(24),
        borderRadius: px2dp(24),
        marginBottom: px2dp(12),
        height: '18%',
    },
    time: {
        color: '#111111',
        fontWeight: '500',
        fontSize: scale(32),
    },
    byTimeText: {
        color: '#111111',
        fontWeight: '500',
        fontSize: scale(28),
    },
    tips: {
        fontWeight: '400',
        color: '#626262',
        fontSize: scale(28),
        lineHeight: px2dp(40),
    },
    t3: {
        fontSize: scale(22),
        color: '#666666',
        width: px2dp(200),
    },
    empity: {
        color: '#a6a6a6',
        fontSize: scale(28),
    },
    activeCourse: {
        color: '#1777FF',
        fontSize: scale(28),
        textAlign: 'center',
        fontWeight: 'bold',
    },
    switchDoctor: {
        backgroundColor: '#fff',
        width: px2dp(180),
        height: px2dp(60),
        borderRadius: px2dp(30),
        justifyContent: 'center',
        alignItems: 'center',
    },
});
